package com.leonzx.base.config.security;

import com.leonzx.base.config.init.UserInit;
import com.leonzx.base.entity.system.Menu;
import com.leonzx.base.entity.system.User;
import com.leonzx.base.service.system.MenuService;
import com.leonzx.base.service.system.UserService;
import com.leonzx.base.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Objects;


/**
 * 自定义认证、授权实现
 */
public class ShiroDbRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    /**
     * 设定Password校验的Hash算法与迭代次数.
     */
    @PostConstruct
    public void initCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(Digests.HASH_ALGORITHM);
        matcher.setHashIterations(Digests.HASH_INTERATIONS);
        setCredentialsMatcher(matcher);
    }

    /**
     * 认证回调函数, 登录时调用.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

        User user = userService.getByUsername(token.getUsername());
        //TODO 获取request 为以后增加ip白名单做准备
        //HttpServletRequest request = (HttpServletRequest) ((WebSubject) SecurityUtils.getSubject()).getServletRequest();
        if (user != null) {
            String salt = user.getUsername();
            //禁用
            //登录权限验证
            if (Objects.equals(Constants.STATE_INVAILD, user.getState())) {
                throw new UnknownAccountException("用户状态无效，请联系管理员");
            }
            return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(salt), getName());
        } else {
            throw new UnknownAccountException("用户名不存在！");
        }
    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        List<Menu> menus;
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (Objects.equals(user.getUsername(), UserInit.ADMIN)) {
            menus = menuService.getAll();
        } else {
            menus = menuService.getAllByUserId(user.getId());
        }
        //取出当前用户所具有URL的菜单以及权限
        menus.forEach(menu -> {
            if (StringUtils.isNotBlank(menu.getUrl())) {
                authorizationInfo.addStringPermission(menu.getUrl());
            }
        });
        return authorizationInfo;
    }

    /**
     * 更新用户授权信息缓存.
     */
    public void clearCachedAuthorizationInfo(User user) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(user, getName());
        clearCachedAuthorizationInfo(principals);
    }

    /**
     * 清除所有用户授权信息缓存.
     */
    public void clearAllCachedAuthorizationInfo() {
        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
        if (cache != null) {
            for (Object key : cache.keys()) {
                cache.remove(key);
            }
        }
    }
}